//
//  AppDelegate+ObserverNetWorkChange.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 15-6-29.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "AppDelegate+ObserverNetWorkChange.h"
#import "AppDelegate+Tip.h"
#import "ProgressGradientView.h"
#import "RSWMessageOperation.h"

NSString *const AppDelegateObserverNetWorkChangeNotification = @"AppDelegateObserverNetWorkChangeNotification";

@implementation AppDelegate (ObserverNetWorkChange)

-(void)setObserverNetWorkChangeCheckTimer:(NSTimer*)timer
{
    [self setAssociatedRetainNonatomicValue:timer withKey:"ObserverNetWorkChangeCheckTimer"];
}

-(NSTimer*)observerNetWorkChangeCheckTimer
{
    NSTimer *timer = [self associatedValueForKey:"ObserverNetWorkChangeCheckTimer"];
    return timer;
}

-(void)fireObserverNetWorkChangeCheckTimer
{
    NSTimer *timer = [self observerNetWorkChangeCheckTimer];
    if(timer == nil)
    {
        timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(observerNetWorkChangeResumeFun) userInfo:nil repeats:YES];
        [timer setFireDate:[NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970] + 5]];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [self setObserverNetWorkChangeCheckTimer:timer];
    }
}

-(void)invalidateObserverNetWorkChangeCheckTimer
{
    NSTimer *timer = [self observerNetWorkChangeCheckTimer];
    [timer invalidate];
    [self setObserverNetWorkChangeCheckTimer:nil];
}

-(NSUInteger)observerNetWorkChangeCheckCount
{
    NSUInteger count = [[self associatedValueForKey:"ObserverNetWorkChangeCheckCount"] unsignedIntegerValue];
    return count;
}

-(void)setObserverNetWorkChangeCheckCount:(NSUInteger)checkCount
{
    [self setAssociatedRetainNonatomicValue:@(checkCount) withKey:"ObserverNetWorkChangeCheckCount"];
}

-(BOOL)observerNetWorkChangeChecking
{
    BOOL checking = [[self associatedValueForKey:"ObserverNetWorkChangeChecking"] boolValue];
    return checking;
}

-(void)setObserverNetWorkChangeChecking:(BOOL)checking
{
    [self setAssociatedRetainNonatomicValue:@(checking) withKey:"ObserverNetWorkChangeChecking"];
}

- (void)addObserverNetWorkChange
{
    [self addMainThreadObserverWithDictionarySelector:@{
XMSNetWorkReachabilityStatusChangedNotification:@"observerNetWorkReachabilityStatusChangedNotification:"}];
}

- (void)observerNetWorkReachabilityStatusChangedNotification:(NSNotification *)noti
{
    if([XLGContext context].m_bLogined == NO)
        return;
    
    XMSNetWorkReachability *reach = [noti object];
    if (reach != [XMSNetWorkReachability reachability])
        return;
    
    [self invalidateObserverNetWorkChangeCheckTimer];
    
    [self setObserverNetWorkChangeCheckCount:0];
    
    XMSNetWorkReachabilityType netstatus = [reach currentReachabilityStatus];
    if (XMSNetWorkReachabilityTypeNotReachable == netstatus)
    {
        if(UIApplicationStateBackground == [UIApplication sharedApplication].applicationState)
        {
            [XMSBackgroundMaintain terminateMaintain];
            return;
        }
        
        if ([XLGContext context].m_bIsoffline == YES)
            return;
        
        [XLGContext context].m_bIsoffline = YES;
        
        [XMSSingleQueue runSyncBlock:^
        {
            [RSWMessageOperation suspendOperatePushNotification];
            [XLGUpdateSession suspendUpdateSessionTimer];
            [XLGSendQueueManager suspendSendQueueManager];
            [XLGDownloadManager suspendDownloadManager];
            [XLGServiceTime endService];
            [CRequestChannelPoolShell stopRequestRunLoop];
        }];
        
        [AppDelegate presentBottomAutoCloseTipViewWithTip:@"网络连接不可用"];
        [NSNotificationCenter postNotification:AppDelegateObserverNetWorkChangeNotification userInfo:@{@"1":@(NO)}];
    }
    else
    {
        if ([XLGContext context].m_bIsoffline == NO)
            return;
        
        if([self observerNetWorkChangeChecking] == YES)
            return;
        
        [XMSSingleQueue runSyncBlock:^
        {
            [CRequestChannelPoolShell startRequestRunLoop];
        }];
        
        [self observerNetWorkChangeResumeFun];
    }
}

-(void)observerNetWorkChangeResumeFun
{
    if ([XLGContext context].m_bIsoffline == NO)
        return;
    
    [ProgressGradientView start];
    
    [self setObserverNetWorkChangeChecking:YES];
    
    if([XLGContext context].m_bIsofflinelogin == NO)
    {
        [XLGUpdateSession foregroundCheckSessionIsTimeoutAsyncCompletion:^(NSInteger nResult, BOOL bIstimeout)
        {
            UIApplicationState state = [UIApplication sharedApplication].applicationState;
            
             DispatchMainThreadAsync(^
             {
                 [ProgressGradientView stop];
                 
                 [self setObserverNetWorkChangeChecking:NO];
                 
                 [self invalidateObserverNetWorkChangeCheckTimer];
                 
                 if ([XLGContext context].m_bIsoffline == NO)
                     return;
            
                 if (state == UIApplicationStateBackground)
                     return;
                 
                 switch (nResult)
                 {
                     case YES:
                     {
                         [XLGContext context].m_bIsoffline = NO;
                         
                         [AppDelegate presentBottomAutoCloseTipViewWithTip:@"网络连接成功"];
                         
                         [NSNotificationCenter postNotification:AppDelegateObserverNetWorkChangeNotification userInfo:@{@"1":@(YES)}];
                         
                         if (bIstimeout == NO)
                         {
                             [XMSSingleQueue runAsyncBlock:^
                             {
                                 if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
                                     return;
                                 
                                 [RSWMessageOperation resumeOperatePushNotification];
                                 [XLGUpdateSession resumeUpdateSessionTimer];
                                 [XLGSendQueueManager resumeSendQueueManager];
                                 [XLGDownloadManager resumeDownloadManger];
                                 [XLGServiceTime startService];
                                 [RSWMessageOperation bindPushAsyncCompletion:^(NSInteger nResult, BOOL bResult, NSError *error)
                                 {
                                     [RSWMessageOperation getChatOfflineMessage:YES complete:^(NSInteger nResult){ }];
                                 }];
                             }];
                         }
                         break;
                     }
                     case TERMINATEREADWRITE:
                     {
                         break;
                     }
                     case PROTOCOLRETOBJNIL:
                     {
                         [XLGContext context].m_bIsoffline = YES;
                         [AppDelegate presentBottomAutoCloseTipViewWithTip:@"当前服务不可用"];
                         [NSNotificationCenter postNotification:AppDelegateObserverNetWorkChangeNotification userInfo:@{@"1":@(NO)}];
                         break;
                     }
                     case NETWORKOFFLINE:
                     {
                         [XLGContext context].m_bIsoffline = YES;
                         [AppDelegate presentBottomAutoCloseTipViewWithTip:@"当前网络不可用，\r请检查网络"];
                         [NSNotificationCenter postNotification:AppDelegateObserverNetWorkChangeNotification userInfo:@{@"1":@(NO)}];
                         break;
                     }
                     default:
                     {
                         [self observerNetWorkChangeResumeCheck];
                         
                         [XLGContext context].m_bIsoffline = YES;
                         [AppDelegate presentBottomAutoCloseTipViewWithTip:@"登录超时，\r应用处于离线操作状态"];
                         [NSNotificationCenter postNotification:AppDelegateObserverNetWorkChangeNotification userInfo:@{@"1":@(NO)}];
                         break;
                     }
                 }
             });
        }];
    }
    else
    {
        //TODO
    }
}

-(BOOL)observerNetWorkChangeResumeCheck
{
    if([self observerNetWorkChangeCheckCount] >= 2)
    {
        [self invalidateObserverNetWorkChangeCheckTimer];
        [self setObserverNetWorkChangeCheckCount:0];
        return NO;
    }
    else
    {
        [self fireObserverNetWorkChangeCheckTimer];
        [self setObserverNetWorkChangeCheckCount:[self observerNetWorkChangeCheckCount] + 1];
    }
    return YES;
}

@end
